package top.kaoshanji.q1ch05a.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import top.kaoshanji.q1ch05a.dao.SpittleRepository;
import top.kaoshanji.q1ch05a.model.Spittle;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/24 11:09
 */
@Controller
@RequestMapping("/spittle")
public class SpittleController {

    private static final String MAX_LONG_AS_STRING = "9223372036854775807";

    private SpittleRepository spittleRepository;

    @Autowired
    public SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

    /**
     * 代码清单-q1ch05a-150页a：在模型中放入最新的spittle列表
     * 请求路径参数...
     * @param max id最大值
     * @param count 数据数量
     * @param model Model
     * @return 视图逻辑名称
     */
    @RequestMapping(value = "/spittleList", method = RequestMethod.GET)
    public String spittleList(@RequestParam(value="max", defaultValue=MAX_LONG_AS_STRING) long max,
                           @RequestParam(value="count", defaultValue="20") int count, Model model) {

        model.addAttribute("spittleList", spittleRepository.findSpittles(max, count));

        return "spittleListPage";
    }

    /**
     * 代码清单-q1ch05a-156页a：通过路径参数接受输入
     * @param spittleId id
     * @param model Model
     * @return 视图逻辑名称
     */
    @RequestMapping(value = "/spittleDetail/{spittleId}", method = RequestMethod.GET)
    public String spittleDetail(@PathVariable("spittleId") long spittleId, Model model) {
        Spittle spittle = spittleRepository.findOne(spittleId);

        model.addAttribute("spittle", spittle);

        return "spittleDetailPage";
    }


}
